package Utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class SpellUtil {
	 /**
	    * 将字符串中的中文转化为拼音,其他字符不变
	    *
	    * @param chinesString
	    * @return
	    */
	    public static String getSpell(String chinesString) {
	        HanyuPinyinOutputFormat format = new
	        HanyuPinyinOutputFormat();
	        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
	        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
	        format.setVCharType(HanyuPinyinVCharType.WITH_V);

	        char[] input = chinesString.trim().toCharArray();
	        String output = "";

	        try {
	            for (int i = 0; i < input.length; i++) {
	                if (java.lang.Character.toString(input[i]).
	                matches("[\\u4E00-\\u9FA5]+")) {
	                    String[] temp = PinyinHelper.
	                    toHanyuPinyinStringArray(input[i],
	                    format);
	                    output += temp[0];
	                } else
	                    output += java.lang.Character.toString(
	                    input[i]);
	            }
	        } catch (BadHanyuPinyinOutputFormatCombination e) {
	            e.printStackTrace();
	        }
	        return output;
	    }
	    
	    /**  
	     * 汉字转换位汉语拼音首字母，英文字符不变  
	     * 同时一致转换为大写字母
	     * @param chines 汉字  
	     * @return 拼音  
	     */     
	    public static String converterToFirstSpell(String chines){             
	         String spellName = "";      
	        final char[] nameChar = chines.subSequence(0, 1).toString().toCharArray();      
	        final HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();      
	         defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);      
	         defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);      
	        for (int i = 0; i < nameChar.length; i++) {      
	            if (nameChar[i] > 128) {      
	                try {      
	                     spellName += PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0].charAt(0);      
	                 } catch (BadHanyuPinyinOutputFormatCombination e) {      
	                     e.printStackTrace();      
	                 }      
	             }else{      
	                 spellName += nameChar[i];      
	             }      
	         }      
	        return spellName.substring(0,1).toUpperCase();
	     }  
}
